﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Web.Security;
using DoeObjects;

namespace DoeLibsMVC.Security
{
    public static class SecurityHelper
    {
        public static bool currentUserIsInStaffGroup()
        {
            if (System.Web.HttpContext.Current.User != null && System.Web.HttpContext.Current.User.IsInRole(UserCategoryHelper.STAFF_CATEGORY))
            {
                return true;
            }

            return false;
        }

        public static DoeObjects.User getCurrentUser()
        {
            return System.Web.HttpContext.Current.User as DoeObjects.User;
        }

        public static string secureString(string clear)
        {

            HashAlgorithm algo = MD5.Create();
            byte[] hash = algo.ComputeHash(Encoding.UTF8.GetBytes(clear));

            StringBuilder sb = new StringBuilder();
            foreach (byte b in hash)
                sb.Append(b.ToString("X2"));

            return sb.ToString();
        }
        public static string generateSalt()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            var bytes = new Byte[32];
            rng.GetBytes(bytes);
            return Convert.ToBase64String(bytes);
        }

        /// <summary>
        /// checks for the user credentials and logs the user in (set cookie, etc.) is the credentials are right
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static LoginStatus login(string username, string password)
        {
            User user;
            if ((user = DoeObjects.User.getUserByMail(username)) != null)
            {
                if (SecurityHelper.secureString(user.Salt + password) == user.Password)
                {
                    if (user.Activated)
                    {
                         //check for activated account
                        if (user.Acceptor == null)
                        {
                            CustomPrincipal customPrincipal = new CustomPrincipal(user.UserId);
                        
                            //create cookie
                            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, "DoeLibS", DateTime.Now, DateTime.Now.AddMinutes(15), false, user.UserId.ToString());

                            string encTicket = FormsAuthentication.Encrypt(authTicket);
                            HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                            System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);

                            //set HttpUser
                            System.Web.HttpContext.Current.User = customPrincipal;

                            return LoginStatus.OK;
                        }
                        else
                        {
                            return LoginStatus.ACCOUNT_NOT_ACTIVATED;
                        }
                    }
                    else
                    {
                        return LoginStatus.ACCOUNT_HAS_EXPIRED;
                    }
                }
                else
                {
                    return LoginStatus.WRONG_PASSWORD;
                }
            }
            else
            {
                return LoginStatus.UNKNOWN_USERNAME;
            }
        }

        /// <summary>
        /// checks if the authCookie is set and if so returns its decrypted value
        /// </summary>
        /// <returns></returns>
        public static string getAuthCookieValue()
        {
            HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                return authTicket.UserData;
            }

            return null;
        }

        public enum LoginStatus
        {
            OK,
            UNKNOWN_USERNAME,
            WRONG_PASSWORD,
            ACCOUNT_NOT_ACTIVATED,
			ACCOUNT_HAS_EXPIRED
        }
    }
}